﻿#pragma execution_character_set("utf-8")
#include "bllchartreader.h"
#include "chartreader.h"
#include "datacenter.h"
#include "logger.h"
#include <QThread>
#include <QDebug>

class bllChartReaderPrivate : public QThread
{
public:
    bllChartReaderPrivate(int ms);
    ~bllChartReaderPrivate();

public:
    void start(const QString *arg = Q_NULLPTR);
    void stop();

protected:
    void run();

private:
    ChartReader *m_newchartreader;
    int m_readInterval;
    volatile bool m_stop;
};

bllChartReaderPrivate::bllChartReaderPrivate(int ms)
    : m_newchartreader(new ChartReader)
    , m_readInterval(ms)
    , m_stop(true)
{
    connect(m_newchartreader, &ChartReader::dataReady, DataCenter::instance(), &DataCenter::dataReady);
    connect(m_newchartreader, &ChartReader::measureError, DataCenter::instance(), &DataCenter::measureError);
    connect(DataCenter::instance(), &DataCenter::setParameter, m_newchartreader, &ChartReader::onSetParameter);
}

bllChartReaderPrivate::~bllChartReaderPrivate()
{
    delete m_newchartreader;
}

void bllChartReaderPrivate::start(const QString *arg)
{
    Q_UNUSED(arg)
    if (m_stop)
    {
        m_stop = false;
        QThread::start();
    }
}

void bllChartReaderPrivate::stop()
{
    if (!m_stop)
    {
        m_stop = true;
        quit();
        wait();
    }
}

bllChartReader:: bllChartReader(int ms)
    : IComponent("bllChartReader")
    , d(new bllChartReaderPrivate(ms))
{
}

bllChartReader::~bllChartReader()
{
    d->stop();
    d->deleteLater();
}

void bllChartReaderPrivate::run()
{
    sysDebug("bllChartReaderPrivate::run() start, thread ID: %d", QThread::currentThreadId());

    bool ret = m_newchartreader->open();
    sysDebug("open chart reader: %d", ret);

    while (!m_stop && ret)
    {// 示波器连接失败，不启动测试
        m_newchartreader->measure();
        QThread::msleep(static_cast<unsigned long>(m_readInterval));
    }

    m_newchartreader->close();
    sysDebug("close chart reader");
    sysDebug("bllChartReaderPrivate::run() stopped.");
}

void bllChartReader::start(const QString *arg)
{
    d->start(arg);
}

void bllChartReader::stop()
{
    d->stop();
}

void bllChartReader::restart(const QString *arg)
{
    stop();
    start(arg);
}
